package be.donovan.gui.helper.components;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



public class CatalogRegistry extends Observable {

	private static Map<ViewI, List<Observer>> registry = new HashMap<ViewI, List<Observer>>();

	private static Map<Class, Set> repository = new HashMap<Class, Set>();

	private static CatalogRegistry instance;

	private static Log logger = LogFactory.getLog(CatalogRegistry.class);
	
	static {
		instance = new CatalogRegistry();
	}

//	public static void register(JComboBox comboBox) {
//		Container parent = comboBox.getParent();
//		while (parent != null && parent.getParent() != null && !ViewI.class.isInstance(parent)) {
//			parent = parent.getParent();
//		}
//		if (ViewI.class.isInstance(parent)) {
//			if (registry.get(parent) == null) {
//				registry.put((ViewI) parent, new ArrayList<Observer>());
//			}
//			registry.get(parent).add((MVCComboBoxModel)comboBox.getModel());
//		}
//		instance.addObserver((MVCComboBoxModel)comboBox.getModel());
//		logger.info("register : " + registry.get(parent).size() + ", " + parent + ", " + ((MVCComboBoxModel)comboBox.getModel()).getClazz());
//	}

	public static void unregister(ViewI view) {
		if (registry.get(view) != null) {
			for (Observer observer : registry.get(view)) {
				instance.deleteObserver(observer);
				logger.info("unregister : " + observer); 
			}
			registry.get(view).clear();
		}
		logger.info("unregistered : " + view);
	}

	public static void add(Class clazz, Set dtos) {
		if (!(repository.containsKey(clazz))){
			repository.put(clazz, new TreeSet());
		}
		if ((dtos != null) && (!(repository.get(clazz).containsAll(dtos)))) {
			repository.get(clazz).addAll(dtos);
			instance.setChanged();
			instance.notifyObservers(dtos);
		}
	}

	
	public static Set getCached(Class clazz) {
		return (repository.containsKey(clazz)) ? repository.get(clazz) : new TreeSet();
	}
	
//	public static boolean isAlreadyRegistered(JComboBox comboBox) {
//		return registry.containsValue(comboBox.getModel());
//	}
}
